import 'dart:async';

import 'package:flutter/material.dart';

class Swiper extends StatefulWidget {
  final List<Widget> images;
  final double height;
  final double width;
  const Swiper(
      {super.key,
      required this.images,
      this.height = double.infinity,
      this.width = double.infinity});

  @override
  State<Swiper> createState() => _SwiperState();
}

class _SwiperState extends State<Swiper> {
  int _currentIndex = 0;
  late PageController _pageController;
  late Timer timer;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 0);

    // 定时器
    timer = Timer.periodic(
      const Duration(seconds: 2),
      (timer) {
        _pageController.animateToPage(
          (_currentIndex + 1) % widget.images.length,
          duration: const Duration(milliseconds: 500), // 跳转动画时长
          curve: Curves.linear, // 动画类型
        );
      },
    );
  }

  // 页面销毁的同时销毁定时器
  @override
  void dispose() {
    super.dispose();
    timer.cancel();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          height: widget.height,
          width: widget.width,
          child: PageView.builder(
            controller: _pageController,
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, index) {
              return widget.images[index % widget.images.length];
            },
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index % widget.images.length;
              });
            },
          ),
        ),
        Positioned(
          // 设置left和right为0，子组件就会占满整行
          left: 0,
          right: 0,
          bottom: 50,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(
              widget.images.length,
              (index) {
                return Container(
                  margin: const EdgeInsets.all(3),
                  width: 10,
                  height: 10,
                  decoration: BoxDecoration(
                    // 根据当前的index来判断小红点的颜色
                    color: index == _currentIndex ? Colors.red : Colors.white,
                    shape: BoxShape.circle,
                  ),
                );
              },
            ),
          ),
        )
      ],
    );
  }
}
